#enconding=utf-8
import os
import requests
from common.kubenetes.kubenetes import get_k8s_pod_info
from common.log.log_config import logger

class Singleton(type):
    def __call__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            cls._instance = super(Singleton, cls).__call__(*args, **kwargs)

        return cls._instance

#设置集群信息
class Cluster(metaclass=Singleton):
    def __init__(self):
        self.cluster_info = self._set_cluster_info()
        self.prometheus_uri = self._set_prometheus_uri()
        self.launcher_uri = self._set_cluster_launcher_uri()
        self.yarn_uri = self._set_cluster_yarn_uri()
        self.rest_server_uri = self._set_rest_server_uri()
        self.user_center_uri = self._set_user_center_uri()

    def get_token_config(self):
        username = os.getenv("PAI_TOKEN_USERNAME", "paictrlcenter@leinao.ai")
        password = os.getenv("PAI_TOKEN_PASSWORD", "123456")

        return dict(username=username, password=password)

    def _set_user_center_uri(self):
        cluster_info =  self.cluster_info
        pod = get_k8s_pod_info(cluster_info['cluter_uri'], 'default', 'rest-server')

        if not pod:
            logger.info("can not get pod:pylon from cluster")
            return None

        for container in pod['spec']['containers']:
            for env in container['env']:
                if "LOGIN_PORT" == env['name']:
                    login_port = env['value']
                if "LOGIN_URL" == env['name']:
                    login_url =  env['value']

        if login_port and login_url:
            return "http://{}:{}".format(login_url, login_port)

        return None

    def get_user_center_uri(self):
        return self.user_center_uri

    def get_rest_server_uri(self):
        return self.rest_server_uri

    def get_prometheus_uri(self):
        return  self.prometheus_uri

    def get_launcher_uri(self):
        return self.launcher_uri

    def get_yarn_uri(self):
        return self.yarn_uri

    def _set_cluster_info(self):
        k8s_api_server_uri = os.getenv("K8S_API_SERVER_URI", "http://192.168.8.82:8080")
        if k8s_api_server_uri:
            return dict(cluter_uri = k8s_api_server_uri)

        raise  Exception("ENV K8S_API_SERVER_URI does not exist")

    def _set_rest_server_uri(self):
        cluster_info =  self.cluster_info
        pod = get_k8s_pod_info(cluster_info['cluter_uri'], 'default', 'pylon')

        if not pod:
            logger.info("can not get pod:pylon from cluster")
            return None

        for container in pod['spec']['containers']:
            for env in container['env']:
                if "REST_SERVER_URI" == env['name']:
                    return env['value']


    def _set_prometheus_uri(self):
        cluster_info =  self.cluster_info
        pod = get_k8s_pod_info(cluster_info['cluter_uri'], 'default', 'pylon')

        if not pod:
            logger.info("can not get pod:pylon from cluster")
            return None

        prometheus_uri = None
        for container in pod['spec']['containers']:
            for env in container['env']:
                if "PROMETHEUS_URI" == env['name']:
                    prometheus_uri =  env['value']
                    break

        logger.info("prometheus_uri is {}".format(prometheus_uri))
        if not prometheus_uri:
            logger.info("prometheus_uri is null")

        #兼容新版和旧版prometheus接口
        response = requests.get("{}/api/v1".format(prometheus_uri))
        logger.info(response.status_code)
        if response.status_code == 404:
             return "{}/prometheus".format(prometheus_uri)

        return prometheus_uri

    def _set_cluster_launcher_uri(self):
        cluster_info = self.cluster_info
        if not cluster_info:
            return None

        pod = get_k8s_pod_info(cluster_info['cluter_uri'], 'default', 'rest-server')
        if not pod:
            logger.info("can not get pod:rest-server from cluster")
            return None

        for container in pod['spec']['containers']:
            for env in container['env']:
                if "LAUNCHER_WEBSERVICE_URI" == env['name']:
                    return env['value']

        return None

    def _set_cluster_yarn_uri(self):
        cluster_info = self.cluster_info

        pod = get_k8s_pod_info(cluster_info['cluter_uri'], 'default', 'rest-server')
        if not pod:
            logger.info("can not get pod:rest-server from cluster")
            return None

        for container in pod['spec']['containers']:
            for env in container['env']:
                if "YARN_URI" == env['name'] or "YARN_WEB_PORTAL_URI" == env['name']:
                    return env['value']

        return None



